package cn.epsilon3.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import cn.epsilon3.common.E3BaseService;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.epsilon3.common.ResultResp;
import cn.epsilon3.constant.ResultEnum;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Security url资源统一拦截器
 */
@Component
public class SecurityUrlInterceptor extends E3BaseService implements HandlerInterceptor {

    private static final Log log = LogFactory.get();

    private static final Integer CLOSE = 1;
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) {
        String requestURI = request.getRequestURI();
        log.info("请求资源url：" + requestURI);
        ConcurrentHashMap<String, Integer> urlMapCache = getUrl();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        if (urlMapCache.isEmpty()) {
            StpUtil.logout();
            ResultResp.resp(response,
                    ResultEnum.SYSTEM_CLOSE.getCode(),
                    ResultEnum.SYSTEM_CLOSE.getMessage());
            return false;
        }
        if (! urlMapCache.containsKey(requestURI)) {
            ResultResp.resp(response,
                    ResultEnum.NOT_FOUND.getCode(),
                    ResultEnum.NOT_FOUND.getMessage());
            return false;
        }
        Integer status = urlMapCache.get(requestURI);
        if (CLOSE.equals(status)) {
            ResultResp.resp(response,
                    ResultEnum.FEATURE_SUSPENDED.getCode(),
                    ResultEnum.FEATURE_SUSPENDED.getMessage());
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }



}

